<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Models\User;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Hash;

/**
 * 用户登录
 * Class AuthController
 * @package App\Api
 */
class AuthController extends Controller
{
    public function login(Request $request)
    {
//        return $request;
        $isLogin = Auth::attempt(['mobile' => $request->mobile, 'password' => $request->password]);
        if ($isLogin) {
            $token = Auth::user()->createToken('user-name');
            return ['message' => '登录成功', 'token' => $token->plainTextToken];
        }
        return $this->error('账号或者密码错误');
    }

    public function register(Request $request, User $user)
    {
        $request->validate([
            'name' => ['required', Rule::unique('users', 'name')],
            'mobile' => ['required', Rule::unique('users', 'mobile')],
            'password' => ['required', 'confirmed', 'between:5,20'],
        ], [
            'name.unique' => '用户名已经存在',
            'mobile.required' => '手机号不能为空',
            'mobile.unique' => '手机号已经被注册',
            'password.required' => '密码不能为空',
        ]);
        $user->name = $request->name;
        $user->email = $request->email;
        $user->mobile = $request->mobile;
        $user->password = Hash::make($request->password);
        $user->save();
        return $this->message('注册成功');
    }

    public function logout()
    {
        Auth::logout();
        return $this->message('退出成功');
    }
}
